const BASE_URL = "https://www.xlshhr.com/beauty-industry";
// const BASE_URL = "http://8.129.113.116:8081/beauty-industry";
// const BASE_URL = "http://8.129.113.116:8082/beauty-industry";

class Request {
  /**
   * Request请求方法
   * @param  {String} url    链接
   * @param  {Objece} params 参数
   * @param  {Boolean} isToken  是否携带usertoken
   * @return {Promise}       包含抓取任务的Promise
   */
  getApi(url, params, isToken, isbinding, isTips) {
    if (isToken === undefined) isToken = true;
    if (isbinding === undefined) isbinding = true;
    if (isTips === undefined) isTips = true;
    let usertoken = wx.getStorageSync('usertoken') || '';
    const promise = new Promise((resolve, reject) => {
      //判断是否需要置入usertoken
      if (isToken) params = Object.assign({
        sessionId: usertoken
      }, params)
      wx.request({
        url: `${BASE_URL}${url}`,
        method: 'POST',
        data: params, //置入usertoken
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: res => {
          if (res.statusCode == 200) {
            if (res.data.code == 1) {
              console.log(res);
              resolve(res);
            } else if (res.data.code == 2) {
              wx.setStorageSync('usertoken', '')
              if (url.indexOf('/account/appletLogin') == -1) {
                getApp().ToLoginlink()
              }
              // wx.navigateTo({
              //   url: '/pages/Login/Login',
              // })
              resolve(res);
            } else if (res.data.code == 3) {
              wx.setStorageSync('usertoken', '')
              if (url.indexOf('/account/appletLogin') == -1) {
                getApp().ToLoginlink()
              }
              resolve(res);
            } else {
              if (isTips) {
                wx.showToast({
                  title: res.data.desc,
                  icon: 'none',
                  duration: 1000
                });
              }
              reject(res);
            }

          } else {
            wx.showToast({
              title: '[' + res.code + '] 服务器出错,请重试',
              icon: 'none',
              duration: 800
            });
            reject();
          }
        },
        fail: err => {
          wx.showToast({
            title: '网络错误',
            icon: 'none',
            duration: 800
          });
          reject();
        },
        complete: res => {

        }
      });
    });

    if (usertoken == '' && isToken) {
      // return new Promise((resolve, reject) => {
      //     wx.showToast({
      //         title: '状态失效，请关闭小程序后，重新打开',
      //         icon: 'none'
      //     });
      // });
    } else {
      return promise;
    }
  }

}

let request = new Request();

module.exports = {
  get: request.getApi,
  post: request.getApi,
  url: BASE_URL
}